const timestamp = () => new Date().getTime();

const list_to_tree = (data, root_id = 0) => {
  let arr = [];

  data.forEach((item) => {
    if (item.pid === root_id) {
      arr.push(item);
      let children = list_to_tree(data, item.id);
      children.length && (item.children = children);
    }
  });

  return arr;
};

const now_time = ()=>{
  const time = new Date()

  const year = time.getFullYear()
  const month = time.getMonth()+1
  const day = time.getDate()
  const hours = time.getHours()
  const minutes = time.getMinutes()
  const seconds = time.getSeconds()
  const milliseconds = time.getMilliseconds()

  return `${year}-${month}-${day} ${hours}:${minutes}${seconds}.${milliseconds}`
}

// const get_all_folder_id = (nodes, pid = 0) => {
//   // let all_node = Array.isArray(nodes)?nodes: [nodes]

//   // 获取该节点的所有子节点
//   const child_nodes = nodes.filter(item => item.pid == pid);
//   if (child_nodes?.length === 0) {
//     return [];
//   } 
//   const result = child_nodes.concat(
//     child_nodes.map((node) => get_all_folder_id(nodes, node.pid)).flat()
//   );

//   return result
// };

function get_all_folder_id(nodes, id) {
  // 获取该节点的所有子节点
  const childNodes = nodes.filter(n => n.pid == id);

  // 如果没有子节点，则返回空数组
  if (childNodes.length === 0) {
    return [];
  }
  // 递归地获取每个子节点的子孙节点，并将它们拼接到当前数组中
  const res = childNodes.concat(
    childNodes.map(node => get_all_folder_id(nodes, node.id)).flat()
  );
  return res
}

module.exports = {
  timestamp,
  list_to_tree,
  get_all_folder_id,
  now_time
};
